﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Collections;
using System.IO;

/// <summary>
/// Summary description for Tree
/// </summary>
public class Tree
{
    public Tree Parent;
    public Tree Root { get { return Parent != null ? Parent.Root : this; } }
    public List<Tree> Children = new List<Tree>();
    public string Value;
    public bool IsFile;
    public string Name { get { return Parent != null ? Value.Substring(Parent.Value.Length + 1) : "Ses Kayıtları"; } }
    public int UniqueId { get { return Value.GetHashCode(); } }
    private Hashtable _All;
    public Hashtable All { get { return Parent != null ? Parent.All : _All == null ? _All = new Hashtable() : _All; } }

    private static Tree _Instance;

    public static Tree Instance
    {
        get
        {
            if (_Instance == null)
            {
                lock (typeof(Tree))
                {
                    if (_Instance == null)
                    {
                        _Instance = BuildTree(HttpContext.Current.Server.MapPath("/m"));
                    }
                }
            }
            return _Instance;
        }
    }

    public static void Invalidate()
    {
        _Instance = null;
    }

    public static Tree BuildTree(string rootPath)
    {
        Tree root = new Tree();
        root.Value = rootPath;
        root.All.Add(0, root);
        root.ReadChildren();
        return root;
    }

    public Tree FindChildByName(string name)
    {
        foreach (Tree child in Children)
        {
            if (child.Name == name)
            {
                return child;
            }
        }
        return null;
    }

    public void ReadChildren()
    {
        foreach (string subFolder in Directory.GetDirectories(Value))
        {
            Tree child = new Tree();
            child.Parent = this;
            child.Value = subFolder;

            All.Add(child.UniqueId, child);

            child.ReadChildren();
            Children.Add(child);
        }

        foreach (string file in Directory.GetFiles(Value, "*.wav"))
        {
            Tree child = new Tree();
            child.Parent = this;
            child.Value = file;
            child.IsFile = true;

            All.Add(child.UniqueId, child);

            Children.Add(child);
        }
    }

    public int FileCount
    {
        get
        {
            int count = 0;
            foreach (Tree child in Children)
            {
                if (child.IsFile)
                {
                    count++;
                }
            }
            return count;
        }
    }

    public override string ToString()
    {
        return Name + (IsFile ? "" : " [" + Children.Count + " Children]");
    }
}
